<?php
/**
 * Created by PhpStorm.
 * User: mrlee
 * Date: 2019-02-25
 * Time: 22:20
 */

namespace app\api\controller;

use app\common\controller\ActionLogs;
use app\common\model\Agent;
use app\common\model\AgentApply;
use app\common\model\AuthRoleUser;
use app\common\model\LoginUsers;
use app\common\model\Merchant;
use app\common\model\MerchantContent;
use app\common\model\Momerchant;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;


class ApplyAgents extends Controller
{

    //提交
    public function apply_agent($param){
        if (empty($param['mobile'])){
            $re_param['return_code'] = "SUCCESS";
            $re_param['return_msg'] = '';
            $re_param['result_code'] = 'FAIL';
            $re_param['result_msg'] = '提交失败：手机号不可为空';
            return $re_param;
        }
        $bus_no = isset($param['bus_no'])?$param['bus_no']:'cardos'.date('YmdHis').'-'.rand(0000,9999);
        $AgentApply = new AgentApply();
        $data = array(
            'bus_no' => $bus_no,
            'name' => trim($param['company_name']),
            'contacts' => trim($param['realname']),
            'tel' => trim($param['mobile']),
            'address' => trim($param['address']),
            'open_url' => trim($param['open_url']),
            'component_appid' => trim($param['component_appid']),
            'component_appsecret' => trim($param['component_appsecret']),
            'component_encodingaeskey' => trim($param['component_encodingaeskey']),
            'component_token' => trim($param['component_token']),
            'requestdomain' => trim($param['requestdomain']),
            'wsrequestdomain' => trim($param['wsrequestdomain']),
            'uploaddomain' => trim($param['uploaddomain']),
            'downloaddomain' => trim($param['downloaddomain']),
            'webviewdomain' => trim($param['webviewdomain']),
            'appid' => $param['wx_pay_appid'],
            'appsecret' => $param['wx_pay_appsecret'],
            'partnerid' => $param['wx_pay_partnerid'],
            'partnerkey' => $param['wx_pay_partnerkey'],
            'apiclient_key' => $param['apiclient_key'],
            'apiclient_cert' => $param['apiclient_cert'],
            'rootca' => $param['apiclient_rootca'],
            'notify_url' => $param['notify_url'],
            'client_ip' => $param['client_ip'],
            'sysid' => $param['sysid'],
            'statu' => 1,
            'check_status' => "W",
//            'sysid' => $param['sysid'],
            'addtime' => time(),
        );
        $data['start_time']=time();
        $data['end_time']=strtotime('+365 day');

        $map['client_ip'] = $param['client_ip'];
        $info = $AgentApply->where($map)->find();
        if ($info){
            if ($info['check_status'] == "Y"){
                $re_param['return_code'] = "SUCCESS";
                $re_param['return_msg'] = '';
                $re_param['result_code'] = 'FAIL';
                $re_param['result_msg'] = '您的IP已提交通过,请勿重复提交';
                return $re_param;
            }else{
                $add = $AgentApply->where($map)->update($data);
            }
        }else{
            $add = $AgentApply->save($data);
        }
        if ($add) {
            $re_param['return_code'] = "SUCCESS";
            $re_param['return_msg'] = '';
            $re_param['result_code'] = 'SUCCESS';
            $re_param['result_msg'] = '提交成功,请耐心等待审核';
            $re_param['data']['items']['bus_no'] = $bus_no;
        } else {
            $re_param['return_code'] = "SUCCESS";
            $re_param['return_msg'] = '';
            $re_param['result_code'] = 'FAIL';
            $re_param['result_msg'] = '提交失败';
        }
        return $re_param;
    }

    //提交物业申请商户
    public function apply_momach($param){
        if (empty($param['mobile'])){
            $re_param['return_code'] = "SUCCESS";
            $re_param['return_msg'] = '';
            $re_param['result_code'] = 'FAIL';
            $re_param['result_msg'] = '提交失败：手机号不可为空';
            return $re_param;
        }
        $username = 'sh'.trim($param['mobile']);
        $password = 'sh'.trim($param['mobile']).'mm';
        $LoginUsers = new LoginUsers();
        $isusername = $LoginUsers->where('username',$username)->find();
        if ($isusername){
            $re_param['return_code'] = "FAIL";
            $re_param['return_msg'] = '';
            $re_param['result_code'] = 'FAIL';
            $re_param['result_msg'] = '用户名已存在';
            return $re_param;
        }
        $Agent = new Agent();
        $agentinfo = $Agent->where(['id'=>$param['agentid']])->find();
        if (!$agentinfo){
            $re_param['return_code'] = "FAIL";
            $re_param['return_msg'] = '';
            $re_param['result_code'] = 'FAIL';
            $re_param['result_msg'] = '代理商信息错误';
            return $re_param;
        }
        $Momerchant = new Momerchant();
        $data['merchant_name'] = trim($param['company_name']);
        $data['sub_mch_id'] = trim($param['wx_pay_partnerid']);
        $data['agent'] = $param['agentid'];
        $data['wx_open_id'] = $agentinfo['wx_open_id'];
        if (!empty($param['img'])) {
            $data['img'] = $param['img'];
        } else {
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';

            $data['img'] = $http_type . $_SERVER['HTTP_HOST'] . '/uploads/mach/default.jpg';
        }
        $param['leibie'] = '其它';
        $param['leibie2'] = '其它';
        $categories = [$param['leibie'] . ',' . $param['leibie2']];
        $data['leibie'] = $param['leibie'];
        $data['leibie2'] = $param['leibie2'];
        //END
        $data['categories'] = json_encode($categories, JSON_UNESCAPED_UNICODE);      //类别
        $data['addtime'] = time();
        $data['tpl_msg_type'] = 3;
        //时间
        $data['start_time'] = time();
        $data['end_time'] = strtotime('+365 day');
        //费率
        $data['wx_service_charge'] = $param['service_charge'];
        $data['ali_service_charge'] = $param['service_charge'];
        $data['pos_service_charge'] = $param['service_charge'];

        $data['momach_type'] = $param['momach_type'];
//        $re_param['$data'] = $data;
//            file_put_contents('/data2/html/payos/test.txt', 'isuser-4:' . json_encode($arr), FILE_APPEND);
        $add = $Momerchant->allowField(true)->validate('momerchant.add')->save($data);
        if ($add == false) {
            $re_param['return_code'] = "SUCCESS";
            $re_param['return_msg'] = '';
            $re_param['result_code'] = 'FAIL';
            $re_param['result_msg'] = $Momerchant->getError();
        } else {
            $top_mid = $Momerchant->id;

            //同步创建账号
            $datas['username'] = trim($username);
            $datas['xingming'] = trim($param['realname']);
            $datas['top_mid'] = $top_mid;
            $datas['level'] = 3001;
            $datas['agent'] = $param['agentid'];
            $datas['password'] = md5($password);
            $datas['tel'] = trim($param['mobile']);
            $datas['createtime'] = time();
            $res = $LoginUsers->allowField(true)->validate(true)->save($datas);
            if ($res) {
                $sdata['role_id'] = 4;
                $sdata['user_id'] = $LoginUsers->id;
                $AuthRoleUser = new AuthRoleUser();
                $AuthRoleUser->save($sdata);
            }
            $re_param['return_code'] = "SUCCESS";
            $re_param['return_msg'] = '';
            $re_param['result_code'] = 'SUCCESS';
            $re_param['result_msg'] = '创建成功';
            $re_param['data']['items']['momach_id'] = $top_mid;
            $re_param['data']['items']['mach_no'] = 0;
                //同步添加门店
            $machres = $this->add_mach(['top_machno'=>$top_mid,'merchant'=>$param['merchant'],'sub_mch_id'=>$data['sub_mch_id']]);
            if ($machres['return_code'] == 'SUCCESS' && $machres['result_code'] == 'SUCCESS' ){
                $re_param['data']['items']['mach_no'] = $machres['data']['items']['mach_no'];
            }else{
                $re_param['result_msg'] = '创建商户成功,创建门店失败';
            }
            //END

//            $re_param['data']['items']['momach_id'] = $datas['top_mid'];
            $re_param['data']['items']['bus_no'] = date('YmdHis').'-'.rand(0000,9999);
        }
        return $re_param;

    }

    //添加门店
    // top_machno   merchant sub_mch_id
    public function add_mach($param){
        $Merchant = new Merchant();
        $Momerchant = new Momerchant();
        $top_mid = $param['top_machno'];
        $momach = $Momerchant->where('id', $top_mid)->find();
        if (!$momach){
            $re_param['return_code'] = "SUCCESS";
            $re_param['return_msg'] = '';
            $re_param['result_code'] = 'FAIL';
            $re_param['result_msg'] = '创建失败,错误的商户信息';
            return $re_param;
        }
        $momach['leibie'] = "其它";
        $momach['leibie2'] = "其它";
        $categories = [$momach['leibie'],$momach['leibie2']];
        $data['leibie'] = $momach['leibie'];
        $data['leibie2'] = $momach['leibie2'];
        if (empty($param['merchant'])) {
            $data['sub_mch_id'] = $momach['sub_mch_id'];
        } else {
            $data['sub_mch_id'] = trim($param['sub_mch_id']);
        }
        $data['merchant'] = trim($param['merchant']);
        $data['top_mid'] = $top_mid;
        $data['wx_open_id'] = $momach['wx_open_id'];
        $data['salesman'] = $momach['salesman'];
        $data['agent'] = $momach['agent'];
        $data['tpl_msg_type'] = $momach['tpl_msg_type'];
        //时间
        $data['times'] = $momach['times'];
        $data['start_time'] = $momach['start_time'];
        $data['end_time'] = $momach['end_time'];
        //费率
        $data['wx_service_charge'] = $momach['wx_service_charge'];
        $data['ali_service_charge'] = $momach['ali_service_charge'];
        $data['pos_service_charge'] = $momach['pos_service_charge'];
        //END
         $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $data['img'] = $http_type . $_SERVER['HTTP_HOST'] . '/uploads/mach/default.jpg';
        $data['categories'] = json_encode($categories, JSON_UNESCAPED_UNICODE);      //类别
        $data['address'] = trim($momach['address']);                   //地址
        $data["MerchantContent"] = array(
            'contacts' => trim($momach['contacts']),
            'tel' => trim($momach['tel']),
            'address' => trim($momach['address']),
        );
        $data['addtime'] = time();
        $data['is_deposit'] = !empty($momach['is_deposit'])?$momach['is_deposit']:"N";
        $res = $Merchant->allowField(true)->together('MerchantContent')->validate('merchant.add')->save($data);
        if (!$res) {
            $re_param['return_code'] = "SUCCESS";
            $re_param['return_msg'] = '';
            $re_param['result_code'] = 'FAIL';
            $re_param['result_msg'] = '创建失败:'.$Merchant->getError();
        } else {
            $re_param['return_code'] = "SUCCESS";
            $re_param['return_msg'] = '';
            $re_param['result_code'] = 'SUCCESS';
            $re_param['result_msg'] = '创建成功';
            $re_param['data']['items']['mach_no'] = $Merchant->id;
            $re_param['data']['items']['bus_no'] = date('YmdHis').'-'.rand(0000,9999);
        }
        return $re_param;
    }

    //修改门店
    public function edit_mach($param){
        $Merchant = new Merchant();
        $data['merchant'] = trim($param['merchant']);
        $data['sub_mch_id'] = trim($param['sub_mch_id']);
        $res = $Merchant->where(['id' => $param['mach_no']])->update($data);
        if (!$res) {
            $re_param['return_code'] = "SUCCESS";
            $re_param['return_msg'] = '';
            $re_param['result_code'] = 'FAIL';
            $re_param['result_msg'] = '修改失败:'.$Merchant->getError();
        } else {
            $re_param['return_code'] = "SUCCESS";
            $re_param['return_msg'] = '';
            $re_param['result_code'] = 'SUCCESS';
            $re_param['result_msg'] = '修改成功';
        }
        return $re_param;
    }

    //删除门店
    public function del_mach($param){
        $Merchant = new Merchant();
        $res = $Merchant->where(['id' => $param['mach_no']])->delete();
        if (!$res) {
            $re_param['return_code'] = "SUCCESS";
            $re_param['return_msg'] = '';
            $re_param['result_code'] = 'FAIL';
            $re_param['result_msg'] = '删除失败:'.$Merchant->getError();
        } else {
            $re_param['return_code'] = "SUCCESS";
            $re_param['return_msg'] = '';
            $re_param['result_code'] = 'SUCCESS';
            $re_param['result_msg'] = '删除成功';
        }
        return $re_param;
    }

}